package com.example.pmxt.modules.region;

import com.example.pmxt.common.Result;
import com.example.pmxt.common.ReturnResult;
import com.example.pmxt.domain.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@Validated
@RequestMapping("/regions")
public class RegionController {

    private RegionService service;

    @Autowired
    public RegionController(RegionService service) {
        this.service = service;
    }

    @GetMapping("/getall")
    public ReturnResult getall(){
        return ReturnResult.buildSuccessResult(service.list());
    }

    @GetMapping("/{parentid}")
    public ReturnResult getbyparentid(@PathVariable String parentid){
        Map<String,Object> map = new HashMap<>();
        map.put("parent_id",parentid);
        return ReturnResult.buildSuccessResult(service.listByMap(map));
    }

    @PostMapping("/addregion")
    public ReturnResult addregion(@RequestBody Region region){
        try {
            if (service.save(region)) {
                return ReturnResult.buildSuccessResult(service.save(region));
            }else {
                return ReturnResult.buildFailureResult("id已经存在");
            }
        } catch (Exception e) {
            return ReturnResult.buildFailureResult("id已经存在",false);
        }
    }

    @DeleteMapping("/{id}")
    public ReturnResult deleteregion(@PathVariable String id){
        try {
            if (service.removeById(id)) {
                return ReturnResult.buildSuccessResult(service.removeById(id));
            }else {
                return ReturnResult.buildFailureResult("id不存在");
            }
        } catch (Exception e) {
            return ReturnResult.buildFailureResult("id不存在");
        }
    }

    @PutMapping("/updateregion")
    public ReturnResult updateregion(@RequestBody Region region){
        try {
            if (service.updateById(region)) {
                return ReturnResult.buildSuccessResult(service.updateById(region));
            }else {
                return ReturnResult.buildFailureResult("id已经存在");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    //@PostMapping定义IP地址映射方法与位置，@ApiOperation是swagger测试注解
    @PostMapping("/uploadregion")
    public ReturnResult excelToDatabase( @RequestParam boolean deleteHistory,
                                         @RequestPart("file") MultipartFile file) {
        Result result = new Result();
        if(service.importFileToDB(deleteHistory, file)){
            return ReturnResult.buildSuccessResult("添加成功",null);
        }else {
            return ReturnResult.buildFailureResult("添加失败",null);
        }
    }

}
